package com.dengqi.mymodule.activity.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.dengqi.mymodule.BaseActivity;
import com.dengqi.mymodule.R;
import com.dengqi.mymodule.fragment.TypeFragment;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;


/**
 * https://www.jianshu.com/p/74c034010d56
 * https://blog.csdn.net/qq_33425116/article/details/52599818
 * https://blog.csdn.net/wangwo1991/article/details/76377063
 */
public class TabLayoutActivity extends BaseActivity{


    private TabLayout tabLayout;
    private ViewPager viewPager;
    private List<String> datas = new ArrayList<>();
    private List<Fragment> mFragments = new ArrayList<>();
    private ViewPagerAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_tablayout);

        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);

        datas.add("test1");
        datas.add("test2");
        datas.add("test3");
        datas.add("test4");
        datas.add("test5");
        datas.add("test6");
        datas.add("test7");
        datas.add("test8");
        datas.add("test9");

        //MODE_SCROLLABLE可滑动的展示
        //MODE_FIXED固定展示
//        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        //设置TabLayout点击事件
        for (int i = 0; i < datas.size(); i++) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "type:"+i);
            mFragments.add(Fragment.instantiate(this, TypeFragment.class.getName(), bundle));
        }
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        adapter.setData(mFragments);
        adapter.setTitle(datas);
        adapter.notifyDataSetChanged();
        tabLayout.setupWithViewPager(viewPager);

        //设置自定义视图
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(getTabView(i));
        }
    }

    /**
     * 自定义方法，提供自定义Tab
     * @param position
     * @return
     */
    public View getTabView(int position) {
        View v = LayoutInflater.from(this).inflate(R.layout.item_bottom, null);
        TextView textView = v.findViewById(R.id.tv_title);
        ImageView imageView = v.findViewById(R.id.iv_icon);
        textView.setText(datas.get(position));
        imageView.setImageResource(R.mipmap.ic_launcher);
        //添加一行，设置颜色
        textView.setTextColor(tabLayout.getTabTextColors());
        return v;
    }
}
